package com.na.tools.search;

import java.util.Random;

public class IpTable {

	private int baseIp, mask, maskReverse; // 0~255
	private static final Random RND = new Random();
	
	public IpTable(String ip) {
		int dot = ip.indexOf('/');
		if (dot <= 0) {
			throw new IllegalArgumentException(ip);
		}
		int maskBit = Integer.parseInt(ip.substring(dot + 1));
		maskReverse = 0xffffffff >>> maskBit;
		mask = ~maskReverse;
		baseIp = ip2int(ip.substring(0, dot));
	}
	
	public String randomIp() {
		int ip = baseIp | RND.nextInt(maskReverse);
		return int2ip(ip);
	}
	
	public static int ip2int(String ip) {
		String[] strs = ip.split("\\.");
		int intIp = (Integer.parseInt(strs[0]) & 0xff) << 24;
		intIp |= (Integer.parseInt(strs[1]) & 0xff) << 16;
		intIp |= (Integer.parseInt(strs[2]) & 0xff) << 8;
		intIp |= (Integer.parseInt(strs[3]) & 0xff);
		return intIp;
	}
	
	public static String int2ip(int ip) {
		return (ip >> 24 & 0xff) + "." + (ip >> 16 & 0xff) + "." + (ip >> 8 & 0xff) + "." + (ip & 0xff);
	}
}
